/**
 * 学习目标：使用Ref获取dom元素、组件实例对象
 * 作用：ref获取dom元素、组件实例对象
 */
import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
  // 1. 创建ref
  iptRef = React.createRef();
  childRef = React.createRef();

  handleClick = () => {
    console.log('input  ----->  ', this.iptRef.current);
    // 3. 通过ref对象.current属性来访问
    this.iptRef.current.focus();
  };

  handleClickChild = () => {
    console.log('  ----->  ', this.childRef.current.state.count);
    this.childRef.current.handleClick();
  };

  render() {
    return (
      <div>
        <input
          type="text"
          // 2. 绑定给dom元素或者组件
          ref={this.iptRef}
        />
        <Child ref={this.childRef}></Child>

        <button onClick={this.handleClick}>点我访问input元素，主动让input获得焦点</button>
        <button onClick={this.handleClickChild}>点我访问子组件</button>
      </div>
    );
  }
}

class Child extends React.Component {
  state = {
    count: 100,
  };

  handleClick = () => {
    alert(this.state.count);
  };

  render() {
    return <h1>我是Child = {this.state.count}</h1>;
  }
}

ReactDOM.render(<App></App>, document.getElementById('root'));
